﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
//Internal Reference Below
using ProtoImaginer.ProtoProject;
using ProtoImaginer.Models;

namespace ProtoImaginer
{
    public partial class MainPage : PhoneApplicationPage
    {
        public static IList<Project> MyProjects = new List<Project>();
        public static string guid = "null";
        protected static Boolean SignedIn = false;

        // Constructor
        public MainPage()
        {
            CreateDatabase();
            MyProjects = FetchAllRecords();
            InitializeComponent();
            checkSign();
            checkProject();
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            App.ViewModel.LoadData();
            Refresh();
        }
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        #region RefreshFunction&Timer

        protected void Refresh()
        {
            MyProjects = FetchAllRecords();
            App.ViewModel.LoadData();
            //Customized Codes Here
            checkSign();
            checkProject();
        }
        void OnTimerTick(object sender, EventArgs e)
        {
            UpdateClock();
        }

        void UpdateClock()
        {
            Refresh();
        }

        protected void checkProject()
        {
            if(MainViewModel.projectListEmpty)
            {
                ProjectListBox.Visibility = Visibility.Collapsed;
                NoProjectNotice.Visibility = Visibility.Visible;
            }
            else
            {
                ProjectListBox.Visibility = Visibility.Visible;
                NoProjectNotice.Visibility = Visibility.Collapsed;
            }
        }

        private void checkSign()
        {
            if (!SignedIn)
            {
                SignInText.Visibility = Visibility.Visible;
                SignUpButton.Visibility = Visibility.Visible;
                SignInButton.Visibility = Visibility.Visible;
                ShareIcon.Visibility = Visibility.Collapsed;
                ShareText.Visibility = Visibility.Collapsed;
                CheckSubmIcon.Visibility = Visibility.Collapsed;
                CheckSubmText.Visibility = Visibility.Collapsed;
                ProfileIcon.Visibility = Visibility.Collapsed;
                ViewProfileText.Visibility = Visibility.Collapsed;
                SignOutText.Visibility = Visibility.Collapsed;
            }
            else
            {
                ShareIcon.Visibility = Visibility.Visible;
                ShareText.Visibility = Visibility.Visible;
                CheckSubmIcon.Visibility = Visibility.Visible;
                CheckSubmText.Visibility = Visibility.Visible;
                ProfileIcon.Visibility = Visibility.Visible;
                ViewProfileText.Visibility = Visibility.Visible;
                SignOutText.Visibility = Visibility.Visible;
                SignInText.Visibility = Visibility.Collapsed;
                SignUpButton.Visibility = Visibility.Collapsed;
                SignInButton.Visibility = Visibility.Collapsed;
            }
        }

        #endregion

        #region DatabaseQueryFunction

        private const string strConnectionString = @"isostore:/protoDataContext.sdf";

        public static void CreateDatabase()
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                if (database.DatabaseExists() == false)
                {
                    database.CreateDatabase();
                    MessageBox.Show("Database Created Successfully!!!");
                }
                //else { MessageBox.Show("Database already exists!!!"); }
            }
        }

        public static void AddNewRecord(Project p)
        {
            if (p.ProjectName.Length == 0)
            {
                MessageBox.Show("null!");
                return;
            }
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                Project newProject = new Project(
                    p.ProjectId,
                    p.ProjectAuthor,
                    p.ProjectName,
                    p.ProjectStatus,
                    p.ProjectDescription,
                    p.ProjectTag,
                    p.ProjectCreateDate,
                    p.ProjectLastModifiedDate
                    );
                database.Projects.InsertOnSubmit(newProject);
                try
                {
                    database.SubmitChanges();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1);
                    database.SubmitChanges();
                }
                MessageBox.Show("Employee Added Successfully!!!");
            }
        }

        public static IList<Project> FetchAllRecords()
        {
            //IList<Project> RecordList = new List<Project>();
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query
                    = from pjt in database.Projects
                      orderby pjt.ProjectLastModifiedDate descending
                      //orderby pjt.Field<DateTime>("ProjectLastModifiedDate")
                      select pjt;
                return query.ToList();
            }
        }
        
        public static Project QueryProjectRecordById(string id) 
        {
            
            IList<Project> RecordList = null;
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query = from pjt in database.Projects where pjt.ProjectId == id.ToString() select pjt;
                RecordList = query.ToList();
            }
            return RecordList[0];
        }

        public static void ListAllProjectRecords()
        {
            IList<Project> PjtList = null;
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query = from pjt in database.Projects select pjt;
                PjtList = query.ToList();
            }
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.AppendLine("Project List");
            foreach (Project pt in PjtList)
            {
                strBuilder.AppendLine("Name - " + pt.ProjectName + " Created On - " + pt.ProjectCreateDate.ToString());
            }
            MessageBox.Show(strBuilder.ToString());
        }

        //NOT WORK
        public static void UpdateRecords(Project p)
        {
            if (p.ProjectName.Length == 0)
            {
                MessageBox.Show("null!");
                return;
            }
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> record = from pjt in database.Projects where pjt.ProjectId == p.ProjectId select pjt;
                Project projectToUpdate = record.FirstOrDefault();
                projectToUpdate.ProjectLastModifiedDate = DateTime.Now;
                projectToUpdate.ProjectDescription = p.ProjectDescription;
                projectToUpdate.ProjectName = p.ProjectName;
                projectToUpdate.ProjectTag = p.ProjectTag;
                database.SubmitChanges();
                IQueryable<Project> recor = from pjt in database.Projects where pjt.ProjectId == p.ProjectId select pjt;
                Project projectToUpdat = recor.FirstOrDefault();
                MessageBox.Show(projectToUpdat.ProjectName);
            }
        }

        public static void DeleteRecord(Project p)
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                IQueryable<Project> query = from pjt in database.Projects where pjt.ProjectId == p.ProjectId select pjt;
                Project PjtToRemove = query.FirstOrDefault();
                database.Projects.DeleteOnSubmit(PjtToRemove);
                database.SubmitChanges();
                MessageBox.Show("Project Deleted Successfully!!!");
            }
        }

        public static void DeleteDatabase()
        {
            using (ProtoDataContext database = new ProtoDataContext(strConnectionString))
            {
                if (database.DatabaseExists())
                {
                    database.DeleteDatabase();
                    MessageBox.Show("Database Deleted Successfully!!!");
                }
            }
        }
        #endregion

        #region Page1_Projects_Functions&Members

        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            Popup popup = new Popup();
            popup.VerticalOffset = 0;
            ProtoProject.NewProjectPopup control = new ProtoProject.NewProjectPopup();
            popup.Child = control;
            popup.IsOpen = true;
            control.OK_Button.Click += (s, args) =>
            {
                popup.IsOpen = false;
                Guid guid;
                // Create and display the value of two GUIDs.
                guid = Guid.NewGuid();
                Project temp = new Project(
                    guid.ToString(),
                    1,
                    control.NewProjectName_TextBox.Text,
                    "No Description",
                    ""
                );
                MainPage.AddNewRecord(temp);
                Refresh();
            };
            control.Cancel_Button.Click += (s, args) =>
            {
                popup.IsOpen = false;
            };
        }

        private void Remove_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.ProjectListBox.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;
            ItemViewModel itemToDelete = selectedListBoxItem.DataContext as ItemViewModel;
            DeleteSelected(MyProjects.ToList(), itemToDelete.ItemID);
            Refresh();
        }

        public void DeleteSelected(List<Project> list, string id)
        {
            foreach (Project p in list)
            {
                if (p.ProjectId == id)
                {
                    DeleteRecord(p);
                }
            }
        }

        // Handle selection changed on ListBox
        private void ProjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (ProjectListBox.SelectedIndex == -1)
                return;
            //NavigationService.Navigate(new Uri("/ProtoProject/ViewProject.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            NavigationService.Navigate(new Uri("/ProtoProject/ViewProject.xaml?selectedItem=" + ProjectListBox.SelectedIndex, UriKind.Relative));
            ProjectListBox.SelectedIndex = -1;
        }

        private void SearchProject_Click(object sender, RoutedEventArgs e)
        {
            //xxxxtesting
            //follow preprocessing
            NavigationService.Navigate(new Uri("/ProtoPage/PageView.xaml?name=", UriKind.Relative));
        }
        #endregion

        #region Page2_Community_Functions&Members
        private void SignInPressed(object sender, RoutedEventArgs e)
        {
            SignedIn = true;
            //Refresh the view
            Refresh();
        }
        private void SignOutAction(object sender, RoutedEventArgs e)
        {
            SignedIn = false;
            //Refresh the view
            Refresh();
        }
        #endregion

        private void MenuItemQuit_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("Menu item 1 works!");
            throw new Exception();
        }

        private void goToHelp(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Miscellaneous/HelpPage.xaml", UriKind.Relative));
        }

    }
}